//
//  UIViewController+HDChatOBO.m
//  app
//
//  Created by D on 15/5/19.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDChatOBO.h"
#import "HDToolView.h"
#import "HDChatOBOResult.h"
#import "HDChatOBOManager.h"
#import "HDChatOBOSendMessageResult.h"
#import "HDActionSheetView.h"
#import "UIImage+Conveniently.h"
#import "HDChatOBOSenImage.h"
#import "HDChatListManager.h"
#import "HDTimeHeaderView.h"
#import "HDChatRangeResult.h"
#import "HDReplyToolButton.h"


static const CGFloat kCartTotalPanelHeight = 120;

static  int timeId = 0 ;

@interface HDChatOBO ()

@property (nonatomic,strong) HDToolView * toolBarView;
@property (nonatomic,strong) HDChatOBOManager * chatOBOManager;
@property (nonatomic,strong) HDChatOBOResult * chatOBOResutl;
@property (nonatomic,strong) HDChatOBOSendMessageResult * chatOBOSendMsgResutl;
@property (nonatomic,strong) HDChatOBOSenImage * chatOBOSendImageResult;
@property (nonatomic,strong) HDChatListManager * chatListManager;
@property (nonatomic,strong) HDChatShopResutl * chatShopResult;
@property (nonatomic,strong) HDChatRangeResult * chatRangeResult;
@property (nonatomic,assign) int ownerAddID;
@property (nonatomic,strong) NSMutableArray * dateArray;
@property (nonatomic,strong) NSMutableArray * messageArray;
@property (nonatomic,strong) NSMutableArray * imageArray;
@property (nonatomic,strong) NSString * messagetime;
@property (nonatomic,assign) BOOL isFirstSend;
@property (nonatomic,strong) NSString * imagePath;
@property (nonatomic,assign) int count;
@property (nonatomic,assign) float lastPosition;
@property (nonatomic,strong) HDMsgHeaderView * msgHeaderView;
@property (nonatomic,strong) HDTimeHeaderView * timeView;
@property (nonatomic,strong) NSMutableArray * scaleImagaArr;
@property (nonatomic,strong) NSMutableArray * highImageArr;
@property (nonatomic,strong) NSMutableArray * timeArr;
@property (nonatomic,strong) UIView * picFatherView;
@property (nonatomic,assign) CGFloat sacle ;
@property (nonatomic,assign) CGFloat heigth;
@property (nonatomic,assign) CGFloat width;
@property (strong,nonatomic) UIButton * emojiBtn;
@property (assign,nonatomic) BOOL keyboardIsShow;
@property (assign,nonatomic) BOOL emojiBoardIsShow;
@property (assign,nonatomic) BOOL isPictureShow;
@property (strong,nonatomic) NSMutableArray * emojiArr;

@end

@implementation HDChatOBO

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.count = 0;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.chat_people_name;
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.dateArray = [NSMutableArray array];
    self.messageArray = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];
    self.timeArr = [NSMutableArray array];
    self.scaleImagaArr = [NSMutableArray array];
    self.highImageArr = [NSMutableArray array];
    self.emojiArr = [NSMutableArray array];
    self.isFirstSend = YES;
    self.picFatherView = [[UIView alloc]init];
    
    self.view.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] >0) {
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectOf(CGPointMake(0, 64),
                                                                    [self.view.ubo ow:UBO_WINDOW.width  oh:UBO_WINDOW.height - 60-64]) style:UITableViewStyleGrouped];
        
        self.tableView.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [self.view addSubview:self.tableView];
        
        
        self.toolBarView = [[HDToolView alloc]initAndFrame:CGRectOf([self.ubo fx:0 fy:1 oy:-52], [self.ubo ow:UBO_WINDOW.width oh:52])];
        self.toolBarView.delegate = self;
        self.toolBarView.messageContent.delegate = self;
        [self.view addSubview:self.toolBarView];

        
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyboard:)];
        [self.tableView addGestureRecognizer:tap];
        

        
        self.chatOBOResutl = [[HDChatOBOResult alloc]initWithTarget:self action:@selector(dealWithGetContentData:)];
        self.chatOBOManager = [HDChatOBOManager shareManager];
        self.chatOBOSendMsgResutl = [[HDChatOBOSendMessageResult alloc]initWithTarget:self action:@selector(dealWithSendMsgData:)];
        self.chatOBOSendImageResult = [[HDChatOBOSenImage alloc]initWithTarget:self action:@selector(dealWithSendImageData:)];
        self.chatShopResult = [[HDChatShopResutl alloc]initWithTarget:self action:@selector(shopMessage:)];
        self.chatRangeResult = [[HDChatRangeResult alloc]initWithTarget:self action:@selector(loseData:)];
        self.chatListManager = [HDChatListManager shareManager];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessage:) name:@"newMessage" object:nil];
        
    }
    
   
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.emojiBoardIsShow == YES) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
    }
    [self.toolBarView.messageContent resignFirstResponder];
    [ApplicationDelegate hideEmojiKeyboard];
    
    self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -60]);
    self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52], [self.ubo ow:UBO_WINDOW.width oh:52]);
    
    
    
     if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] >0)
     {
         self.count = 0;
         self.lastPosition = self.tableView.contentOffset.y;
         if ([[NSUserDefaults standardUserDefaults]objectForKey:@"sendImageload"]) {
             [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"sendImageload"];
             
             [self upLoadFaceWithMsgTime:@""];
             
         }
         
         
         if (![self.chatOBOManager fmdbIncludeChatPeople:self.chat_people_uid] || ![self.chatOBOManager fmdbInculdeContentDataWithPeople:self.chat_people_uid]) {
             //        [self resultChatContent];
             //        无表无数据
             
             if (self.isShop.integerValue == 1) {
                 if (self.shop_price.integerValue != 0) {
                     
                     NSDictionary * dic = @{@"name":self.shop_name,
                                            @"image":self.shop_image,
                                            @"price":self.shop_price,
                                            @"isShop":@"1"};
                     HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                    
                     msgHeaderView.delegate = self;
                     self.tableView.tableHeaderView = msgHeaderView;
                     
                 }
                 [self sendShopResultWithAuto:@"0"];
             }else if (self.isShop.integerValue == 2)
             {
                 NSDictionary * dic = @{@"reserve_number":self.reserve_number,
                                        @"reserve_price":self.reserve_price,
                                        @"reserve_status":self.reserve_status,
                                        @"isShop":@"0"};
                 HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                 msgHeaderView.delegate = self;
                 self.tableView.tableHeaderView = msgHeaderView;
             }
             
             
         }else
         {
             self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
             if (self.chatOBOResutl.dataSourceArray.count == 0) {
                 
                 if (self.isShop.integerValue == 1) {
                     NSDictionary * dic = @{@"name":self.shop_name,
                                            @"image":self.shop_image,
                                            @"price":self.shop_price,
                                            @"isShop":@"1"};

                     HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                     msgHeaderView.delegate = self;
                     self.tableView.tableHeaderView = msgHeaderView;
                     [self sendShopResultWithAuto:@"0"];
                     
                 }else if (self.isShop.integerValue == 2)
                 {
                     NSDictionary * dic = @{@"reserve_number":self.reserve_number,
                                            @"reserve_price":self.reserve_price,
                                            @"reserve_status":self.reserve_status,
                                            @"isShop":@"0"};
                     HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                     msgHeaderView.delegate = self;
                     self.tableView.tableHeaderView = msgHeaderView;
                 }
             }
             
             NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
             [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
             //判断是否有遗落消息
             NSMutableArray * loseDataArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"loseData"];
             
             for (int i = 0; i < loseDataArr.count; i ++) {
                 if (self.chat_people_pmid.integerValue
                      == [[[loseDataArr objectAtIndex:i]objectForKey:@"pmid"]integerValue]) {
                     //需要拉取遗失数据
                     NSString * ownerAddId = [NSString stringWithFormat:@"%lu",(unsigned long)[[self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid]count]];
                     
                     NSDictionary * params = @{@"startid":[[loseDataArr objectAtIndex:i]objectForKey:@"startid"],
                                               @"endid":[[loseDataArr objectAtIndex:i]objectForKey:@"endid"],
                                               @"pmid":self.chat_people_pmid};
                     [self.chatOBOManager loadLoseChatData:self.chatRangeResult People:self.chat_people_uid Params:params OwnerAddId:ownerAddId];
                     
                 }
                 
                 
             }
             
             
             
             
         }

     }else
     {
         UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"登陆后客服可提供更好的服务~" delegate:self cancelButtonTitle:nil otherButtonTitles:@"先逛逛",@"我要登陆", nil];
         [av show];
     }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillChangeFrameNotification object:nil];
    }
#endif
    
//    if (self.tableView.tableHeaderView != nil) {
    
        self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -10]);
        
//    }
    
    
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (self.emojiBoardIsShow == YES) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
    }
    [self.toolBarView.messageContent resignFirstResponder];
    [ApplicationDelegate hideEmojiKeyboard];
    
    self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -60]);
    self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52], [self.ubo ow:UBO_WINDOW.width oh:52]);
    
 
        
        self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -10]);
        
  
    
}

-(void)loseData:(HDChatRangeResult*)rt
{
    if (rt.success) {
        self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
                
        NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark - alterview 代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            DLog(@"跳转");
            [self.navigationController popViewControllerAnimated:YES];
            
        }
            break;
        case 1:
        {
//            DLog(@"跳回去");
            
            HDAppDelegate* app = (HDAppDelegate*)[[UIApplication sharedApplication]delegate];
            app.storyBoard = [UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil];
            
            UIViewController * loginOut = [app.storyBoard instantiateViewControllerWithIdentifier:@"login"];
            loginOut.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:loginOut animated:NO];
        }
            break;
            
        default:
            break;
    }
}



#pragma mark - 发送商品信息
-(void)sendShopResultWithAuto:(NSString*)Auto
{
    if (self.shop_id.integerValue != 0) {
        
        NSDictionary * params = @{@"mtype":@"3",
                                  @"product_id":self.shop_id,
                                  @"auto":Auto,
                                  @"fuid":self.chat_people_uid};
        
        if (Auto.integerValue == 0) {
            [self.chatOBOManager sendShopContent:self.chatShopResult People:self.chat_people_uid Params:params];
        }else
        {
            NSTimeInterval time = [[NSDate date]timeIntervalSince1970];
            long long int currDate = (long long int)time;
            NSString * timeStr = [NSString stringWithFormat:@"%lld",currDate];
            
            NSDictionary * dict = @{@"title":self.shop_name,
                                   @"title_pic":self.shop_image,
                                   @"sale_price":self.shop_price};
            NSString *returnString=[dict JSONString];
            NSString * ownerAddId = [NSString stringWithFormat:@"%d",self.chatOBOResutl.dataSourceArray.count];
            
            NSDictionary * listDic = @{@"name":self.chat_people_name,
                                       @"face":self.chat_people_face,
                                       @"lastTalk":@"商品信息",
                                       @"time":timeStr,
                                       @"uid":self.chat_people_uid};
            
            NSArray * array = @[ownerAddId,timeStr,@"0",self.chat_people_uid,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],@"0",@"0",@"",@"0",@"0",@"0",@"3",returnString,@"111",@"0"];
            
            if (self.chatOBOResutl.dataSourceArray.count == 0) {
                [self.chatOBOManager createFmdbWithPmid:self.chat_people_uid];
            }
            
            [self.chatOBOManager saveDatetoDBWithPeople:self.chat_people_uid Array:array ListDic:listDic];
            
            NSDictionary * dic = @{@"state":@"1"};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"flower" object:self userInfo:dic];
            
            self.toolBarView.messageContent.text = @"";
            self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
            [self.tableView reloadData];
            NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
            [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            
//            DLog(@"fuid = %@",self.chat_people_uid);
            
            self.count ++;
            
            
            //再向服务器发送请求
            [self.chatOBOManager sendChatContent:self.chatOBOSendMsgResutl People:self.chat_people_uid Params:params Refresh:@"1" sendMsgTime:timeStr Index:@"0" OwnerAddId:ownerAddId];

        }
        
//        [self.chatOBOManager sendChatContent:self.chatOBOSendMsgResutl People:self.chat_people_uid Params:params Refresh:@"1" sendMsgTime:nil Index:nil];
        
    }
}
#pragma mark - 商品信息的数据处理
-(void)shopMessage:(HDChatShopResutl*)rt
{
    if (rt.success) {
        NSLog(@"1111");
    }
    
}
#pragma mark - 点击发送链接
-(void)sendShopLinkToServer:(UIButton *)button
{
    [self sendShopResultWithAuto:[NSString stringWithFormat:@"%d",button.tag]];
}


#pragma mark - 发送获取聊天记录请求
-(void)resultChatContent
{
    NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid]count]];
    [self.chatOBOManager loadChatContentData:self.chatOBOResutl People:self.chat_people_uid SendMsgTime:@"no" OwnerAddId:ownerAddId];
}
#pragma mark - 聊天记录数据处理
-(void)dealWithGetContentData:(HDChatOBOResult*)rt
{
    [self.tableView endRefreshingAll];
    if (rt.success) {
        [self.tableView.nothingRefreshView remove];
        self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
        
        if (self.chatOBOResutl.dataSourceArray.count == 0) {
            
            if (self.isShop.integerValue == 1) {
                NSDictionary * dic = @{@"name":self.shop_name,
                                       @"image":self.shop_image,
                                       @"price":self.shop_price,
                                       @"isShop":@"1"};
                HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                msgHeaderView.delegate = self;
                self.tableView.tableHeaderView = msgHeaderView;
              
                
            }else if (self.isShop.integerValue == 2)
            {
                NSDictionary * dic = @{@"reserve_number":self.reserve_number,
                                       @"reserve_price":self.reserve_price,
                                       @"reserve_status":self.reserve_status,
                                       @"isShop":@"0"};
                HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                msgHeaderView.delegate = self;
                self.tableView.tableHeaderView = msgHeaderView;
            }
        }
        
        [self.tableView reloadData];
       NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        [self sendShopResultWithAuto:@"0"];
        
    }else
    {
        self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
        if (self.chatOBOResutl.dataSourceArray.count == 0) {
            
            if (self.isShop.integerValue == 1) {
                NSDictionary * dic = @{@"name":self.shop_name,
                                       @"image":self.shop_image,
                                       @"price":self.shop_price,
                                       @"isShop":@"1"};
                HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                msgHeaderView.delegate = self;
                self.tableView.tableHeaderView = msgHeaderView;
                [self sendShopResultWithAuto:@"0"];
                
            }else if (self.isShop.integerValue == 2)
            {
                NSDictionary * dic = @{@"reserve_number":self.reserve_number,
                                       @"reserve_price":self.reserve_price,
                                       @"reserve_status":self.reserve_status,
                                       @"isShop":@"0"};
                HDMsgHeaderView * msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
                msgHeaderView.delegate = self;
                self.tableView.tableHeaderView = msgHeaderView;
            }
        }

    }
}


#pragma mark - textview代理
-(void)textViewDidBeginEditing:(UITextView *)textView
{
   
    [ApplicationDelegate hideEmojiKeyboard];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
    self.toolBarView.messageContent = textView;
    [self.toolBarView.messageContent becomeFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (self.emojiBoardIsShow == YES && self.keyboardIsShow == YES) {
        [ApplicationDelegate hideEmojiKeyboard];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
    }
}
#pragma mark - 隐藏键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.toolBarView.messageContent resignFirstResponder];
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
//        DLog(@"长度 = %lu",(unsigned long)self.toolBarView.messageContent.text.length);
        
        if (self.toolBarView.messageContent.text.length <= 120 && self.toolBarView.messageContent.text.length > 0) {
            
            NSTimeInterval time = [[NSDate date]timeIntervalSince1970];
            long long int currDate = (long long int)time;
            NSString * timeStr = [NSString stringWithFormat:@"%lld",currDate];
            
            NSString * codeMsg = [Tool emojiStrEncoding:[Tool emojiStrUnicodeEncoding:self.toolBarView.messageContent.text]];
            
            NSString* messagetime = [NSString stringWithFormat:@"sendMessageTime_%d",timeId++];
            [[NSUserDefaults standardUserDefaults] setObject:timeStr forKey:messagetime];
            [[NSUserDefaults standardUserDefaults] setObject:codeMsg forKey:timeStr];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
            [self.dateArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:messagetime]];
            [self.messageArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:timeStr]];
//            DLog(@"content = %@",self.messageArray);
            [self sendMsgWithContent:codeMsg];
            return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
            
        }else
        {
            if (self.toolBarView.messageContent.text.length == 0){
                UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"提示" message:@"不能发空消息~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [av show];
                 [self performSelector:@selector(dimissAlert:) withObject:av afterDelay:1.0];
            }else
            {
                UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"提示" message:@"超过了120字" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [av show];
                 [self performSelector:@selector(dimissAlert:) withObject:av afterDelay:2.0];
            }
        }
        
        
    }
   
    return YES;
}

-(void)dimissAlert:(UIAlertView*)baseAlert
{
    [baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    
}

#pragma mark - 发送消息
-(void)sendMsgWithContent:(NSString*)content
{
    //先插入数据库
    
    for (int i = 0; i < self.dateArray.count; i++) {
        
        if (self.isFirstSend == YES) {
            
            if (i == self.dateArray.count-1) {
                NSString * timeid = [self.dateArray objectAtIndex:i];
                NSString * message = [self.messageArray objectAtIndex:i];
                NSString * temp_msgid = [NSString stringWithFormat:@"%d",i];
                NSString * ownerAddId = [NSString stringWithFormat:@"%lu",(unsigned long)[[self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid]count]];
                
                NSDictionary * listDic = @{@"name":self.chat_people_name,
                                           @"face":self.chat_people_face,
                                           @"lastTalk":message,
                                           @"time":timeid,
                                           @"uid":self.chat_people_uid};
                
                NSArray * array = @[ownerAddId,timeid,message,self.chat_people_uid,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],temp_msgid,@"0",@"",@"0",@"0",@"0",@"0",@"0",@"111",@"0"];
                
                if (self.chatOBOResutl.dataSourceArray.count == 0) {
                    [self.chatOBOManager createFmdbWithPmid:self.chat_people_uid];
                }
                
                [self.chatOBOManager saveDatetoDBWithPeople:self.chat_people_uid Array:array ListDic:listDic];
            
                
                self.toolBarView.messageContent.text = @"";
//                sleep(2);
                
                
//                DLog(@"fuid = %@",self.chat_people_uid);
                NSDictionary * params = @{@"fuid":self.chat_people_uid,
                                          @"content":message};
                
                self.count ++;
                
                
                //再向服务器发送请求
                [self.chatOBOManager sendChatContent:self.chatOBOSendMsgResutl People:self.chat_people_uid Params:params Refresh:@"1" sendMsgTime:timeid Index:temp_msgid OwnerAddId:ownerAddId];
                
                self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
                [self.tableView reloadData];
                NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
                [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                

            }
        }else
        {
            if ([content isEqualToString:[self.messageArray objectAtIndex:i]]) {
                
                NSString * timeid = [self.dateArray objectAtIndex:i];
                NSString * message = [self.messageArray objectAtIndex:i];
                NSString * temp_msgid = [NSString stringWithFormat:@"%d",i];
                NSString * ownerAddId = [NSString stringWithFormat:@"%d",i];
                
                NSDictionary * listDic = @{@"name":self.chat_people_name,
                                           @"face":self.chat_people_face,
                                           @"lastTalk":message,
                                           @"time":timeid,
                                           @"uid":self.chat_people_uid};
                
                NSArray * array = @[ownerAddId,timeid,message,self.chat_people_uid,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],temp_msgid,@"0",@"",@"0",@"0",@"0",@"0",@"111",@"0"];
                
                if (self.chatOBOResutl.dataSourceArray.count == 0) {
                    [self.chatOBOManager createFmdbWithPmid:self.chat_people_uid];
                }
                
                [self.chatOBOManager saveDatetoDBWithPeople:self.chat_people_uid Array:array ListDic:listDic];
                
                self.toolBarView.messageContent.text = @"";
                self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
                [self.tableView reloadData];
                NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
                [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                
                NSDictionary * params = @{@"fuid":self.chat_people_uid,
                                          @"content":message};
                
                //再向服务器发送请求
                [self.chatOBOManager sendChatContent:self.chatOBOSendMsgResutl People:self.chat_people_uid Params:params Refresh:@"1" sendMsgTime:timeid Index:temp_msgid OwnerAddId:ownerAddId];
                
                NSDictionary * dic = @{@"state":@"1"};
                [[NSNotificationCenter defaultCenter] postNotificationName:@"flower" object:self userInfo:dic];
                
            }

        }
        
    }
    
    
   
}





#pragma mark - tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.chatOBOResutl.dataSourceArray.count;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * cellIdentifier = @"cellIdentifier";
    HDMessageCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];
    if (cell == nil) {
 
        cell = [[HDMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier uid:[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"] view:self.picFatherView scaleArrs:self.scaleImagaArr highPictureArr:self.highImageArr];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    cell.delegate = self;
    HDMessageModel * model = self.chatOBOResutl.dataSourceArray[[indexPath section]];
   
    [cell cellWithModel:model otherFace:self.chat_people_face rowNumber:[indexPath section]];
    cell.backgroundView = nil;
    
    
    
    return cell;
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HDMessageModel * model = self.chatOBOResutl.dataSourceArray[[indexPath section]];
//    DLog(@"%f",model.textHeight);
   
    if (model.myType.integerValue == 3) {
        return 100;
    }else if (model.picture.length > 1){
        return 132;
    }else{
        return 44;
    }
 
}


#pragma mark -  headerView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section >= 1) {
        HDMessageModel * model_last =  self.chatOBOResutl.dataSourceArray[section];
        HDMessageModel * model_no_last = self.chatOBOResutl.dataSourceArray[section-1];
        if (model_last.time.integerValue - model_no_last.time.integerValue > 1800) {
            
            self.timeView = [[HDTimeHeaderView alloc]initWithDic:model_last.time];
//            self.timeView.backgroundColor = [UIColor redColor];
//            NSString * sectionStr = [NSString stringWithFormat:@"%d",section];
//            [self.timeArr addObject:sectionStr];
            
            return self.timeView;
            
        }else
            return nil;
    }else
        return nil;
    
    
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    
    if (self.shop_id.integerValue != 0 && section == self.chatOBOResutl.dataSourceArray.count- self.count-1 && !self.tableView.tableHeaderView) {
        
        if (self.isShop.integerValue == 1) {
            self.tableView.tableHeaderView = nil ;
            NSDictionary * dic = @{@"name":self.shop_name,
                                   @"image":self.shop_image,
                                   @"price":self.shop_price,
                                   @"isShop":@"1"};
            self.msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
            self.msgHeaderView.delegate = self;
            return self.msgHeaderView;
        }else if (self.isShop.integerValue == 2)
        {
            self.tableView.tableHeaderView = nil ;
            NSDictionary * dic = @{@"reserve_number":self.reserve_number,
                                   @"reserve_price":self.reserve_price,
                                   @"reserve_status":self.reserve_status,
                                   @"isShop":@"0"};
            self.msgHeaderView = [[HDMsgHeaderView alloc]initWithDic:dic];
            self.msgHeaderView.delegate = self;
            return self.msgHeaderView;
        }else
        {
            return nil;
        }

        
    }else
        return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section > 0) {
        HDMessageModel * model_last =  self.chatOBOResutl.dataSourceArray[section];
        HDMessageModel * model_no_last = self.chatOBOResutl.dataSourceArray[section-1];
        
        if (model_last.time.integerValue - model_no_last.time.integerValue > 10)
        {
            NSString * sectionStr = [NSString stringWithFormat:@"%d",section];
            [self.timeArr addObject:sectionStr];
        }
        
    }
    
    for (int i = 0 ; i < self.timeArr.count; i++ ) {
        if (section == [[self.timeArr objectAtIndex:i]integerValue]) {
            return 40;
        }
    }
    
    if (section == 0 && !self.tableView.tableHeaderView){
        return 20;
    }else if (section == 0 && self.tableView.tableHeaderView) {
        return 30;
    }else if (section == self.chatOBOResutl.dataSourceArray.count- self.count  && !self.tableView.tableHeaderView){
        return 40;
    }else if (section == 0 && self.msgHeaderView && !self.tableView.tableHeaderView){
        return 20;
    }
    else
    return 20;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (self.shop_id.integerValue != 0 && section == self.chatOBOResutl.dataSourceArray.count- self.count -1) {
        return 100;
    }
    
    return 0.1;
}

#pragma mark - 处理发送消息数据
-(void)dealWithSendMsgData:(HDChatOBOSendMessageResult*)rt
{
    if (rt.success) {
        
        if (self.dateArray.count != 0 && self.messageArray.count !=0) {
            [self.dateArray removeObjectAtIndex:rt.index.integerValue];
            [self.messageArray removeObjectAtIndex:rt.index.integerValue];
            
        }
        
        self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
        [self.tableView reloadData];
        NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        
        
        
        
    }else if (rt.failure){
        self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
        [self.tableView reloadData];
        NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        //        [self.chatOBOManager deleteDataToDb:self.chat_people_uid WithTime:rt.time];
        
    }
}

#pragma mark - 收到新消息

-(void)newMessage:(NSNotification*)info
{
    self.count ++;
    
    self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
    //    DLog(@"count = %lu",(unsigned long)self.chatOBOResutl.dataSourceArray.count);
    [self.tableView reloadData];
    NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
    [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removeOnePageRed" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removeListRed" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removeCellRed" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removePeoRedPoint" object:nil];

}



#pragma mark - 键盘弹出时调用的方法
#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification*)notification {
    if (nil == self.toolBarView.messageContent) {
        return;
    }
    
    NSDictionary *userInfo = [notification userInfo];
    
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    
    CGRect textFrame = self.toolBarView.frame;//当前UITextView的位置
    float textY = textFrame.origin.y + textFrame.size.height;//得到UITextView下边框距离顶部的高度
    float bottomY = self.view.frame.size.height - textY;//得到下边框到底部的距离
    //    if(bottomY >= keyboardRect.size.height ){//键盘默认高度,如果大于此高度，则直接返回
    //
    //        return;
    //    }
    float moveY = keyboardRect.size.height - bottomY;
    
//    [self moveInputBarWithKeyboardHeight:moveY withDuration:animationDuration];
    
//    self.tableView.frame = CGRectMake(0, 64+keyboardRect.size.height, SCREEN_WIDTH, SCREEN_HEIGHT-64-keyboardRect.size.height-UF(110));
    
    self.keyboardIsShow = YES;
    
    self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo ow:UBO_WINDOW.width   oh:UBO_WINDOW.height-64-keyboardRect.size.height-60]);
    self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52-keyboardRect.size.height], [self.ubo ow:UBO_WINDOW.width oh:52]);
    
    
        self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo ow:UBO_WINDOW.width   oh:UBO_WINDOW.height-64-keyboardRect.size.height-10]);
   
    
    if (self.chatOBOResutl.dataSourceArray.count != 0) {
        NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    
    
}

//键盘被隐藏的时候调用的方法
-(void)keyboardWillHide:(NSNotification*)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    self.keyboardIsShow = NO;
    
//    [self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];
    
    self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -60]);
    self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52], [self.ubo ow:UBO_WINDOW.width oh:52]);
    
    
        
        self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -10]);
        
    
    
    if (self.chatOBOResutl.dataSourceArray.count != 0){
        NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    
   
}
#pragma mark 移动view
-(void)moveInputBarWithKeyboardHeight:(float)_CGRectHeight withDuration:(NSTimeInterval)_NSTimeInterval{
    
    CGRect rect = self.view.frame;
    
    rect.origin.y = -_CGRectHeight;//view往上移动
    
    self.view.frame = rect;
    
    
}




#pragma mark - 消息发送中
-(void)flowerShowWithState:(NSString *)state ActivityView:(UIActivityIndicatorView *)flower Button:(UIButton *)failBtn
{
    
    if (flower.tag == self.chatOBOResutl.dataSourceArray.count-1) {
        if (state.integerValue == 1) {
            [flower setHidden:NO];
            [flower startAnimating];
        }else if (state.integerValue == 0){
            [flower stopAnimating];
            [flower setHidden:YES];
        }else if (state.integerValue == 2){
            [flower stopAnimating];
            [failBtn setHidden:NO];
            
        }

    }
    
    
    
}

#pragma mark - 点击重新发送
-(void)againSendMessage:(HDFailureButton *)failBtn ActivityView:(UIActivityIndicatorView *)flower
{
    [failBtn setHidden:YES];
    self.isFirstSend = NO;
    if (failBtn.isPicture == YES) {
        [self upLoadFaceWithMsgTime:failBtn.titleLabel.text];
    }else
    {
        [self sendMsgWithContent:failBtn.titleLabel.text];

    }
}

#pragma mark - 选择图片
-(void)clickMianViewButtons:(HDReplyToolButton *)sender
{
    switch (sender.tag ) {
        case 0:
        {
            
            if (sender.isEmoji == YES) {
                self.emojiBtn = sender;
                self.keyboardIsShow = NO;
                sender.isEmoji = NO;
                [self.toolBarView.messageContent resignFirstResponder];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"1"}];
                [ApplicationDelegate showEmojiKeyboard];
                ApplicationDelegate.emojiKeyboard.delegate = self;
                self.emojiBoardIsShow = YES;
                
                 self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT  oh:-64-ApplicationDelegate.emojiKeyboard.frame.size.height-52]);
                self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52-ApplicationDelegate.emojiKeyboard.frame.size.height], [self.ubo ow:UBO_WINDOW.width oh:52]);
                
        
                    
                    self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT  oh:-14-ApplicationDelegate.emojiKeyboard.frame.size.height-52]);
                    
               
                
                
                
            }else
            {
                sender.isEmoji = YES;
                self.emojiBoardIsShow = NO;
                [sender setBackgroundImage:[UIImage imageNamed:@"btn_publish_openEmoji"] forState:UIControlStateNormal];
                [ApplicationDelegate hideEmojiKeyboard];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
                
                    [self.toolBarView.messageContent becomeFirstResponder];
                
                
            }
            
            
            
        }
            break;
        case 1:
        {
            
            [self.toolBarView.messageContent resignFirstResponder];
            if (self.emojiBoardIsShow == YES) {
                
                self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -60]);
                self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52], [self.ubo ow:UBO_WINDOW.width oh:52]);
                [ApplicationDelegate hideEmojiKeyboard];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
                
                
               
                    
                    self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo ow:UBO_WINDOW.width oh:UBO_WINDOW.height - 64 -10]);
                    
                
                
            }
            [self creatSheet];
        }
        default:
            break;
    }

}

-(void)lmbangEmojiView:(LMBangEmojiView *)emojiView EmojiDidClickedWithEmojiString:(NSString *)emojiString
{
    self.toolBarView.messageContent.text = [NSString stringWithFormat:@"%@%@",self.toolBarView.messageContent.text,emojiString];
    
    [self.emojiArr addObject:emojiString];
    
}
-(void)lmbangEmojiViewBackspaceButtonDidClicked:(LMBangEmojiView *)emojiView
{
    self.toolBarView.messageContent.text = [self.toolBarView.messageContent.text stringByReplacingOccurrencesOfString:[self.emojiArr lastObject] withString:@""options:NSRegularExpressionSearch range:NSMakeRange(0, self.toolBarView.messageContent.text.length)];
    [self.emojiArr removeLastObject];
    
}
-(void)lmbangEmojiViewCancelButtonDidClicked:(LMBangEmojiView *)emojiView
{
    
}
-(void)lmbangEmojiViewSubmitButtonDidClicked:(LMBangEmojiView *)emojiView
{
    if (self.toolBarView.messageContent.text.length <= 120 && self.toolBarView.messageContent.text.length > 0) {
        
        NSTimeInterval time = [[NSDate date]timeIntervalSince1970];
        long long int currDate = (long long int)time;
        NSString * timeStr = [NSString stringWithFormat:@"%lld",currDate];
        
        NSString * codeMsg = [Tool emojiStrEncoding:[Tool emojiStrUnicodeEncoding:self.toolBarView.messageContent.text]];
        
        NSString* messagetime = [NSString stringWithFormat:@"sendMessageTime_%d",timeId++];
        [[NSUserDefaults standardUserDefaults] setObject:timeStr forKey:messagetime];
        [[NSUserDefaults standardUserDefaults] setObject:codeMsg forKey:timeStr];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        [self.dateArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:messagetime]];
        [self.messageArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:timeStr]];
        //            DLog(@"content = %@",self.messageArray);
        [self sendMsgWithContent:codeMsg];
      
        
    }else
    {
        if (self.toolBarView.messageContent.text.length == 0){
            UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"提示" message:@"不能发空消息~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [av show];
            [self performSelector:@selector(dimissAlert:) withObject:av afterDelay:1.0];
        }else
        {
            UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"提示" message:@"超过了120字" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [av show];
            [self performSelector:@selector(dimissAlert:) withObject:av afterDelay:2.0];
        }
    }
    
    

}



#pragma mark - 点击小相机
-(void)creatSheet
{
    HDActionSheetView *actv = [[HDActionSheetView alloc] initWithTitle:nil cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选",nil];
    actv.syActionSheetActionBlock = ^(UIButton *actionBtn){
        
        if (actionBtn.tag == kBtnCaccleTag + 1)
        {
            SYLog(@"%@",actionBtn.titleLabel.text);
            [self takePhoto];
            
        }
        else if (actionBtn.tag == kBtnCaccleTag + 2)
        {
            SYLog(@"%@",actionBtn.titleLabel.text);
            [self localPhoto];
        }
    };
    [actv showSYActionSheet];
    
}

#pragma mark - 打开照相机
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
        picker.sourceType = sourceType;
        
        [self presentViewController:picker animated:NO completion:nil];
    }else
    {
        
    }
}
#pragma mark - 打开相册
-(void)localPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:NO completion:nil];
}
#pragma mark - 保存图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //    [picker.navigationItem.rightBarButtonItem setTitle:@"取消"];
    
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        //        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
//    image = [UIImage OriginImage:image scaleToSize:CGSizeMake(480, 480) fileToRatio:0.8];
    

    NSString * imageName = [NSString stringWithFormat:@"mypic_%d.jpg",++timeId];
    [self saveImage:image WithName:imageName];
    [picker dismissViewControllerAnimated:NO completion:nil];
    

    NSTimeInterval time = [[NSDate date]timeIntervalSince1970];
    long long int currDate = (long long int)time;
    NSString * timeStr = [NSString stringWithFormat:@"%lld",currDate];

    
    NSString * imageTime = [NSString stringWithFormat:@"sendImageTime_%d",timeId];
    [[NSUserDefaults standardUserDefaults] setObject:timeStr forKey:imageTime];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"sendImageload"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.imageArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:imageTime]];
//    [self.dateArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:imageTime]];
//    [self.messageArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:timeStr]];

//    [self.face_img setImage:image];
    
    
}

- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    
    
    if (tempImage.size.width > 720.0f && tempImage.size.height < 720.0f) {
        self.sacle = [XCommon scaleFromWidthOrHeight:tempImage.size.width];
        self.width = 720.0f;
        self.heigth = tempImage.size.height * self.sacle;
        
        
    }else if (tempImage.size.width < 720.0f && tempImage.size.height > 720.0f)
    {
        self.sacle = [XCommon scaleFromWidthOrHeight:tempImage.size.height];
        self.heigth = 720.0f;
        self.width = tempImage.size.width * self.sacle;
        
    }else if (tempImage.size.width > 720.0f && tempImage.size.height > 720.0f)
    {
        if (tempImage.size.width > tempImage.size.height) {
            
            self.sacle = [XCommon scaleFromWidthOrHeight:tempImage.size.width];
            self.width = 720.0f;
            self.heigth = tempImage.size.height * self.sacle;
        
            
        }else if (tempImage.size.width < tempImage.size.height)
        {
            self.sacle = [XCommon scaleFromWidthOrHeight:tempImage.size.height];
            self.heigth = 720.0f;
            self.width = tempImage.size.width * self.sacle;
            
        }else
        {
            self.width = 720.0f;
            self.heigth = 720.0f;
        }
        
    }else
    {
        self.width = tempImage.size.width;
        self.heigth = tempImage.size.height;
    }
    
    NSData* imageData = [UIImage dataOriginImage:tempImage scaleToSize:CGSizeMake(self.width, self.heigth) fileToRatio:0.8];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}
#pragma mark - 发送图片请求
-(void)upLoadFaceWithMsgTime:(NSString*)content
{
    
    for (int i = 0; i < self.imageArray.count; i ++) {
        
        if (self.isFirstSend == YES) {
            if (i == self.imageArray.count-1) {
                
                NSString * timeid = [self.imageArray objectAtIndex:i];
                
                self.imagePath = [NSString stringWithFormat:@"%@/mypic_%d.jpg",[self documentFolderPath],timeId];
                NSData * data = [NSData dataWithContentsOfFile:self.imagePath];
                
                
                NSString * temp_msgid = [NSString stringWithFormat:@"%d",i];
                NSString * ownerAddId = [NSString stringWithFormat:@"%lu",(unsigned long)[[self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid]count]];
                
                
                NSDictionary * listDic = @{@"name":self.chat_people_name,
                                           @"face":self.chat_people_face,
                                           @"lastTalk":@"",
                                           @"time":timeid,
                                           @"uid":self.chat_people_uid};

                NSArray * array = @[ownerAddId,timeid,@"0",self.chat_people_uid,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],@"0",@"0",self.imagePath,@"0",@"0",@"0",@"0",@"0",@"111",@"0"];
                
                if (self.chatOBOResutl.dataSourceArray.count == 0) {
                    [self.chatOBOManager createFmdbWithPmid:self.chat_people_uid];
                }
                
                [self.chatOBOManager saveDatetoDBWithPeople:self.chat_people_uid Array:array ListDic:listDic];
                
                NSDictionary * dic = @{@"state":@"1"};
                [[NSNotificationCenter defaultCenter] postNotificationName:@"flower" object:self userInfo:dic];
                self.toolBarView.messageContent.text = @"";
                self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
                [self.tableView reloadData];
                NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
                [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                
                
                NSDictionary * params = @{@"name" : @"image",
                                          @"fileName" : @"pic.jpg",
                                          @"mimeType" : @"image/jpg"};
                [self.chatOBOManager sendChatImage:self.chatOBOSendImageResult Params:params ImageData:data sengMsgTime:timeid Index:temp_msgid People:self.chat_people_uid OwnerAddId:ownerAddId];
                
            }
        }else
        {
            if ([content isEqualToString:[self.imageArray objectAtIndex:i]]) {
                
                NSString * timeid = [self.imageArray objectAtIndex:i];
                
                self.imagePath = [NSString stringWithFormat:@"%@%@",[self documentFolderPath],@"/mypic.jpg"];
                NSData * data = [NSData dataWithContentsOfFile:self.imagePath];
                
                NSString * temp_msgid = [NSString stringWithFormat:@"%d",i];
                NSString * ownerAddId = [NSString stringWithFormat:@"%d",i];
                
                NSDictionary * listDic = @{@"name":self.chat_people_name,
                                           @"face":self.chat_people_face,
                                           @"lastTalk":@"",
                                           @"time":timeid,
                                           @"uid":self.chat_people_uid};
                
                NSArray * array = @[ownerAddId,timeid,@"0",self.chat_people_uid,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],@"0",@"0",self.imagePath,@"0",@"0",@"0",@"0",@"111",@"0"];
                [self.chatOBOManager saveDatetoDBWithPeople:self.chat_people_uid Array:array ListDic:listDic];
                
                NSDictionary * dic = @{@"state":@"1"};
                [[NSNotificationCenter defaultCenter] postNotificationName:@"flower" object:self userInfo:dic];
                self.toolBarView.messageContent.text = @"";
                self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
                [self.tableView reloadData];
                NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
                [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                
                
                NSDictionary * params = @{@"name" : @"image",
                                          @"fileName" : @"pic.jpg",
                                          @"mimeType" : @"image/jpg"};
                [self.chatOBOManager sendChatImage:self.chatOBOSendImageResult Params:params ImageData:data sengMsgTime:timeid Index:temp_msgid People:self.chat_people_uid OwnerAddId:ownerAddId];
                
            }

        
        }
        
    }

}
#pragma mark - 图片返回处理
-(void)dealWithSendImageData:(HDChatOBOSenImage*)rt
{
    if (rt.success) {
//        DLog(@"picture = %@",rt.picture);
        NSDictionary * params = @{@"fuid":self.chat_people_uid,
                                  @"image":rt.picture,
                                  @"width":rt.wight,
                                  @"height":rt.hight};
       
        
        
        [self.chatOBOManager sendChatContent:self.chatOBOSendMsgResutl People:self.chat_people_uid Params:params Refresh:@"1" sendMsgTime:rt.messageTime Index:rt.index OwnerAddId:rt.ownerId];
        
    }else if (rt.failure){
        self.chatOBOResutl.dataSourceArray = [self.chatOBOManager arrayFromFmdbWithPmid:self.chat_people_uid];
        [self.tableView reloadData];
        NSIndexPath *lastRow = [NSIndexPath indexPathForRow:0 inSection:self.chatOBOResutl.dataSourceArray.count - 1];
        [self.tableView scrollToRowAtIndexPath:lastRow atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }

}


#pragma mark 从文档目录下获取Documents路径
- (NSString *)documentFolderPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}

#pragma mark - 点击隐藏键盘
-(void)hideKeyboard:(UITapGestureRecognizer*)tap
{
    if (self.emojiBoardIsShow == YES) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeimage" object:@{@"sign":@"0"}];
    }
    
    
    [ApplicationDelegate hideEmojiKeyboard];
    [self.toolBarView.messageContent resignFirstResponder];
    self.tableView.frame = CGRectOf(CGPointMake(0, 64),[self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT  oh:-116]);
    self.toolBarView.frame = CGRectOf([self.ubo fx:0 fy:1 oy:-52], [self.ubo fw:UB_WIDTH oh:52]);
    
   
        
       self.tableView.frame = CGRectOf(CGPointMake(0, 14),[self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT  oh:-66]);;
        
   
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int currentPostion = scrollView.contentOffset.y;
    if (currentPostion - self.lastPosition > 10) {
        //下滑
        self.lastPosition = currentPostion;
//        [self.toolBarView.messageContent resignFirstResponder];
        
    }else if (self.lastPosition - currentPostion > 10)
    {
        //上滑
//        self.lastPosition = currentPostion;
        
    }
}


-(void)didReceiveMemoryWarning
{
    
}
@end







